package com.tomato.config;

import com.tomato.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {
    private final JwtUtil jwtUtil;

    public JwtAuthenticationInterceptor(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行OPTIONS请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        // 从请求头中获取token
        String authHeader = request.getHeader("Authorization");
        System.out.println("[Interceptor] Authorization header: " + authHeader); // 添加调试输出

        // 如果Authorization头不存在，尝试从参数中获取
        if (authHeader == null || authHeader.trim().isEmpty()) {
            String tokenParam = request.getParameter("token");
            if (tokenParam != null && !tokenParam.trim().isEmpty()) {
                return validateToken(tokenParam);
            }
            throw new RuntimeException("缺少有效的Token");
        }

        // 处理Authorization头
        String token;
        if (authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
        } else {
            // 如果没有Bearer前缀，直接使用整个值
            token = authHeader;
        }

        return validateToken(token);
    }

    private boolean validateToken(String token) {
        if (!jwtUtil.validateToken(token)) {
            throw new RuntimeException("无效的Token");
        }

        // 获取用户ID和剩余有效时间
        Long userId = jwtUtil.getUserIdFromToken(token);
        String remainingTime = jwtUtil.getRemainingTime(token);
        log.info("用户 {}，Token验证通过，剩余有效时间: {}", userId, remainingTime);

        return true;
    }
}